package com.ruitaowang.core.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisUtil<T> {

	@Autowired
	private RedisTemplate<String,T> redisTemplate;


	/**
	 * 设置失效时间 插入数据
	 *
	 * @param key 唯一键值
	 * @param value data数据
	 * @param timeout 失效时间
	 * @param type 时间单位
	 */
	public void set(String key,T value,Integer timeout,TimeUnit type){
		redisTemplate.opsForValue().set(key, value, timeout, type);
	}

	/**
	 * 删除数据
	 *
	 * @param key 唯一键值
	 */
	public void delete(String key){
		redisTemplate.delete(key);
	}

	/**
	 * 不设置 失效时间 插入数据
	 *
	 * @param key 唯一键值
	 * @param value data数据
	 */
	public void set(String key,T value){
		redisTemplate.opsForValue().set(key, value);
	}

	/**
	 * 查询数据
	 *
	 * @param key 唯一键值
	 * @return T
	 */
	public T get(String key){
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 检查key 是否存在
	 *
	 * @param key 唯一键值
	 * @return boolean
	 */
	public boolean hasKey(String key){
		return redisTemplate.hasKey(key);
	}

	public void set2Hash(String key,String hashKey,T value){
		redisTemplate.opsForHash().put(key, hashKey, value.toString());
	}
	public T getHash(String key,String hashKey){
		Object object = redisTemplate.opsForHash().get(key, hashKey);
		System.out.println(object);
		return null;
	}
	
	public void set2List(String key,T value){
		redisTemplate.opsForList().leftPush(key, value);
	}
	
	public T getList(String key){
		return redisTemplate.opsForList().leftPop(key);
	}
	public T getListOne(String key){
		Long size = redisTemplate.opsForList().size(key);

		return redisTemplate.opsForList().index(key, size-1);
	}
}
